<template>
  <div class="company-detail-page">
    <el-breadcrumb separator="/" class="mb-4">
      <el-breadcrumb-item :to="{ path: '/company' }">主体管理</el-breadcrumb-item>
      <el-breadcrumb-item>主体详情</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card v-if="loading" class="mb-4">
      <div class="text-center py-8">
        <el-icon class="el-icon--loading"><Loading /></el-icon>
        <span class="ml-2">加载中...</span>
      </div>
    </el-card>

    <!-- 主体信息不存在时显示 -->
    <el-card v-else-if="!companyInfo.id" class="mb-4">
      <div class="text-center py-12">
        <el-icon class="text-primary text-5xl mb-4"><Document /></el-icon>
        <h3 class="text-xl font-medium mb-2">主体信息不存在</h3>
        <p class="text-gray-500 mb-6">您还没有完善主体信息，请点击下方按钮进行设置</p>
        <el-button type="primary" @click="navigateToAdd">完善主体信息</el-button>
      </div>
    </el-card>

    <!-- 主体信息详情 - 使用el-descriptions优化显示 -->
    <template v-else>
      <el-card class="mb-4">
        <!-- <template #header>
          <div class="card-header">
            <h2 class="text-xl font-semibold text-gray-800">{{ companyInfo.name }}</h2>
            <span class="text-gray-500 text-sm ml-2">{{ companyInfo.shortName }}</span>
          </div>
        </template> -->

        <!-- 主体概览信息 -->
        <el-descriptions :column="2" border class="mb-4">
          <el-descriptions-item label="公司名称">{{ companyInfo.name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="公司名称">{{ companyInfo.shortName || '-' }}</el-descriptions-item>
          <!-- <el-descriptions-item label="公司编号">{{ companyInfo.companyCode || '-' }}</el-descriptions-item> -->
          <!-- <el-descriptions-item label="主体类型">
            <dict-tag :options="subject_type" :value="companyInfo.subjectType.code" />
          </el-descriptions-item> -->
          <el-descriptions-item label="主体状态">
            <el-tag :type="getSubjectStatusTagType(companyInfo.subjectStatus.code)">
              {{ getSubjectStatusName(companyInfo.subjectStatus.code) }}
            </el-tag>
          </el-descriptions-item>
         
           <el-descriptions-item label="会员状态">
            <dict-tag :options="member_enum" :value="companyInfo.memberMode.code" />
          </el-descriptions-item>


        </el-descriptions>

        <!-- 联系信息 -->
        <h3 class="text-lg font-medium text-gray-700 mb-3">联系信息</h3>
        <el-descriptions :column="2" border class="mb-4">
          <el-descriptions-item label="联系人1">{{ companyInfo.contactPerson1 || '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系方式1">{{ companyInfo.contact1 || '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系人2">{{ companyInfo.contactPerson2 || '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系方式2">{{ companyInfo.contact2 || '-' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 地址信息 -->
        <h3 class="text-lg font-medium text-gray-700 mb-3">地址信息</h3>
        <el-descriptions :column="1" border class="mb-4">
          <el-descriptions-item label="完整地址">{{ getFullAddress() }}</el-descriptions-item>
        </el-descriptions>

      </el-card>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="showEditDialog">编辑主体信息</el-button>
      </div>
    </template>

    <!-- 编辑主体信息弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑主体信息" width="700px" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="editFormRef" :model="editForm" label-width="100px" :rules="rules" class="mt-2">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="主体全称" prop="name">
              <el-input v-model="editForm.name" placeholder="请输入主体全称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="主体简称" prop="shortName">
              <el-input v-model="editForm.shortName" placeholder="请输入主体简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人1" prop="contactPerson1">
              <el-input v-model="editForm.contactPerson1" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式1" prop="contact1">
              <el-input v-model="editForm.contact1" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人2" prop="contactPerson2">
              <el-input v-model="editForm.contactPerson2" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式2" prop="contact2">
              <el-input v-model="editForm.contact2" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="地址信息" prop="province">
              <el-cascader
                v-model="regionValue"
                :options="regionData"
                :props="{ checkStrictly: false }"
                clearable
                placeholder="请选择省市区"
                @change="handleCompanyRegionChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="detailAddress">
              <el-input v-model="editForm.detailAddress" placeholder="请输入详细地址" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { updateCompany,getCompanyDetail,completeCompany2 } from '@/api/company';
import { regionData, codeToText, textToCode } from 'element-china-area-data';

const { member_enum,subject_type } = toRefs<any>(proxy?.useDict('member_enum','subject_type'));
import { CompanyVO } from '@/api/company/types';
import { Document, Loading } from '@element-plus/icons-vue';

const router = useRouter();
const route = useRoute();
const loading = ref(true);
const companyInfo = ref<CompanyVO>({} as CompanyVO);

// 编辑弹窗相关
const editDialogVisible = ref(false);
const editFormRef = ref<InstanceType<typeof ElForm>>();
const submitLoading = ref(false);
// 省市区级联值（编码数组）
const regionValue = ref<string[]>([]);
const editForm = reactive<Partial<CompanyVO>>({
  id: '',
  name: '',
  shortName: '',
  contactPerson1: '',
  contact1: '',
  contactPerson2: '',
  contact2: '',
  province: '',
  city: '',
  district: '',
  detailAddress: ''
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入主体全称', trigger: 'blur' }],
  shortName: [{ required: true, message: '请输入主体简称', trigger: 'blur' }],
  contactPerson1: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contact1: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  province: [{ required: true, message: '请选择省市区', trigger: 'change' }]
};

// 获取主体详情
const fetchCompanyDetail = async () => {
  try {
    loading.value = true;
    // 尝试调用实际API获取数据
    try {
      const response = await getCompanyDetail();
      companyInfo.value = response.data.company || {};
    } catch (apiError) {
      console.warn('API调用失败，使用模拟数据:', apiError);
      // 如果API调用失败，使用模拟数据
      companyInfo.value = {
        id: 1,
        companyCode: 'BILL-2024-0001',
        subjectType: 3,
        name: '飞鹏科技有限公司',
        shortName: '飞鹏科技',
        signature: 'FP',
        contact1: '0574-88888888',
        contactPerson1: '张三',
        contact2: '13800138000',
        contactPerson2: '李四',
        province: '浙江省',
        city: '宁波市',
        district: '海曙区',
        detailAddress: '科技园区88号飞鹏大厦15层',
        memberMode: 2,
        memberStatus: 1,
        memberExpireTime: '2025-12-31',
        subjectStatus: 1
      } as CompanyVO;
    }
  } catch (error) {
    console.error('获取主体信息失败:', error);
    // 确保companyInfo始终是对象
    companyInfo.value = {} as CompanyVO;
  } finally {
    loading.value = false;
  }
};

// 导航到添加页面
const navigateToAdd = () => {
  router.push('/company/add');
};

// 显示编辑弹窗
const showEditDialog = () => {
  // 复制当前公司信息到编辑表单
  Object.assign(editForm, companyInfo.value);
  // 根据中文名称回显为编码数组供级联选择器显示
  try {
    const pName = editForm.province as string;
    const cName = editForm.city as string;
    const dName = editForm.district as string;
    const pNode = (TextToCode as any)[pName];
    const cNode = pNode?.[cName];
    const dNode = cNode?.[dName];
    if (pNode?.code && cNode?.code && dNode?.code) {
      regionValue.value = [pNode.code, cNode.code, dNode.code];
    } else {
      regionValue.value = [];
    }
  } catch (e) {
    regionValue.value = [];
  }
  editDialogVisible.value = true;
};

// 提交编辑表单
const handleSubmit = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();
    submitLoading.value = true;

    // 创建提交数据的副本，确保枚举类型转换为code值
    const submitData = { ...editForm };
    
    // 处理枚举类型，确保提交的是code值
    // 会员模式
    if (submitData.memberMode && typeof submitData.memberMode === 'object' && submitData.memberMode.code !== undefined) {
      submitData.memberMode = submitData.memberMode.code;
    }
    
    // 会员状态
    if (submitData.memberStatus && typeof submitData.memberStatus === 'object' && submitData.memberStatus.code !== undefined) {
      submitData.memberStatus = submitData.memberStatus.code;
    }
    
    // 主体类型
    if (submitData.subjectType && typeof submitData.subjectType === 'object' && submitData.subjectType.code !== undefined) {
      submitData.subjectType = submitData.subjectType.code;
    }
    
    // 主体状态
    if (submitData.subjectStatus && typeof submitData.subjectStatus === 'object' && submitData.subjectStatus.code !== undefined) {
      submitData.subjectStatus = submitData.subjectStatus.code;
    }

    // 调用API更新数据
    const response = await completeCompany2(submitData);
    
    // 更新显示的公司信息
    Object.assign(companyInfo.value, editForm);
    editDialogVisible.value = false;

    // 显示成功提示
    ElMessage({
      message: '修改成功',
      type: 'success'
    });
  } catch (error) {
    console.error('提交表单失败:', error);
    ElMessage({
      message: '修改失败，请重试',
      type: 'error'
    });
  } finally {
    submitLoading.value = false;
  }
};



// 获取主体类型标签类型
const getSubjectTypeTagType = (type: number): string => {
  const typeMap: Record<number, string> = {
    1: 'info',
    2: 'success',
    3: 'primary'
  };
  return typeMap[type] || 'default';
};

// 获取主体状态名称
const getSubjectStatusName = (status): string => {
  return status === 'Y' ? '正常' : '冻结';
};

// 获取主体状态标签类型
const getSubjectStatusTagType = (status): string => {
  return status === 'Y' ? 'success' : 'danger';
};

// 获取会员模式名称
const getMemberModeName = (mode: number): string => {
  return mode === 1 ? '免费会员' : '付费会员';
};

// 获取会员模式标签类型
const getMemberModeTagType = (mode: number): string => {
  return mode === 1 ? 'info' : 'primary';
};

// 获取会员状态名称
const getMemberStatusName = (status: number): string => {
  return status === 1 ? '有效' : '无效';
};

// 获取会员状态标签类型
const getMemberStatusTagType = (status: number): string => {
  return status === 1 ? 'success' : 'warning';
};

// 格式化日期
const formatDate = (dateStr: string): string => {
  if (!dateStr) return '';
  return new Date(dateStr).toLocaleDateString('zh-CN');
};

// 获取完整地址
const getFullAddress = (): string => {
  const { province, city, district, detailAddress } = companyInfo.value;
  const addressParts = [province, city, district, detailAddress].filter(Boolean);
  return addressParts.join(' ') || '-';
};

// 页面加载时获取数据
onMounted(() => {
  fetchCompanyDetail();
});
// 省市区级联选择变更处理（编码转中文）
const handleCompanyRegionChange = (value: string[]) => {
  if (Array.isArray(value) && value.length > 0) {
    const [p, c, d] = value;
    editForm.province = p ? (codeToText as any)[p] || '' : '';
    editForm.city = c ? (codeToText as any)[c] || '' : '';
    editForm.district = d ? (codeToText as any)[d] || '' : '';
  } else {
    editForm.province = '';
    editForm.city = '';
    editForm.district = '';
  }
};
</script>

<style scoped>
.company-detail-page {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.action-buttons {
  margin-top: 20px;
  text-align: right;
}

/* 美化描述列表样式 */
:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-descriptions__label) {
  background-color: #fafafa;
  font-weight: 500;
}

:deep(.el-descriptions__content) {
  padding: 12px 16px;
}

/* 统一标签与内容宽度 */
:deep(.el-descriptions__body) {
  width: 100%;
}
:deep(.el-descriptions__table) {
  width: 100%;
  table-layout: fixed;
}
:deep(.el-descriptions__label),
:deep(.el-descriptions__content) {
  width: 50%;
}

/* 弹窗样式优化 */
:deep(.el-dialog__body) {
  max-height: 60vh;
  overflow-y: auto;
  padding-bottom: 20px;
}
</style>
